//  13366360230
//  loginViewController.m
//  XDBaseFrameWork
//
//  Created by xindao on 14-9-24.
//  Copyright (c) 2014年 XD-XY. All rights reserved.
//

#import "loginViewController.h"
#import "RegisterViewController.h"
#import "RegisterFinishUserInfoViewController.h"
#import "forgetPasswordViewController.h"

#import "APService.h"

#define RIGHTBUTTONFRAME(aHeight) CGRectMake(UI_SCREEN_WIDTH-12-44,0+aHeight,44,44)
@interface loginViewController ()
{
    CGRect mrect1;
    CGRect mrect2;
    CGRect mrect3;
    CGRect mrect4;
    CGRect mrect5;
}
@end

@implementation loginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:YES];
    [self removeKeyboardNotification];
}
-(void)removeKeyboardNotification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide) name:UIKeyboardWillHideNotification object:nil];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.leftBtn.hidden = NO;
    self.titleLabel.text = @"登录";
    self.contentView.backgroundColor = UIColorFromRGB(0xffffefa);
    
    UIButton *registerButton = [self createButtonOnNavigationWithRect:RIGHTBUTTONFRAME(0) normalImg:nil highlightImg:nil];
    [registerButton setTitle:@"注册" forState:UIControlStateNormal];
    [registerButton addTarget:self action:@selector(registerButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    [registerButton setTitleColor:NAVIGATIONTITLECOLORE forState:UIControlStateNormal];
    [self.navigationBarView addSubview:registerButton];

    
//    UIView *headerBgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 40)];
//    headerBgView.backgroundColor = [UIColor whiteColor];
//    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0,headerBgView.frame.size.height-1/2.0, UI_SCREEN_WIDTH, 1/2.0)];
//    lineView.backgroundColor = UIColorFromRGB(0xd3d2d2);
//    [headerBgView addSubview:lineView];
//    [self.contentView addSubview:headerBgView];
    
    logoImageView = [[UIImageView alloc]init];
    logoImageView.frame =CGRectMake((UI_SCREEN_WIDTH-80)/2, 35, 90, 90);
    logoImageView.backgroundColor = [UIColor clearColor];
    logoImageView.image = [UIImage imageNamed:@"Icon@2x"];
    logoImageView.layer.masksToBounds = YES;
    logoImageView.layer.cornerRadius = 8.0f;
    [self.contentView addSubview:logoImageView];
    [self.view bringSubviewToFront:self.navigationBarView];
    
//    finishButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    finishButton.frame =  CGRectMake(10, 5, 40, 30);
//    [finishButton setTitle:@"完成" forState:UIControlStateNormal];
//    [finishButton addTarget:self action:@selector(finishButtonPressed) forControlEvents:UIControlEventTouchUpInside];
//    finishButton.titleLabel.textColor = [UIColor blackColor];
//    UIView *assoryView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 40)];
//    assoryView.backgroundColor = [UIColor clearColor];
//    [assoryView addSubview:finishButton];
    
    
    registerField = [[UITextField alloc]initWithFrame:CGRectMake(20, 180,(UI_SCREEN_WIDTH - 20*2), 40)];
    registerField.placeholder = @"点击输入注册时的手机号";
    registerField.textAlignment = NSTextAlignmentLeft;
    registerField.tag = 333;
    registerField.clearButtonMode = UITextFieldViewModeWhileEditing;
    registerField.keyboardType = UIKeyboardTypeNumberPad;
    registerField.delegate = self;
    registerField.borderStyle = UITextBorderStyleRoundedRect;
    UIImageView *pwdLeftView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    pwdLeftView.image = [UIImage imageNamed:@"userNumber"];
    pwdLeftView.backgroundColor = [UIColor clearColor];
    registerField.leftView = pwdLeftView;
    registerField.leftView.hidden = NO;
    registerField.hidden = NO;
    registerField.leftViewMode  = UITextFieldViewModeAlways;
    [self.contentView addSubview:registerField];
    


    newPassWord = [[UITextField alloc]initWithFrame:CGRectMake(20,height_y(registerField)+20,(UI_SCREEN_WIDTH - 20*2), 40)];
    newPassWord.hidden = NO;
    newPassWord.placeholder = @"请输入密码";
    newPassWord.textAlignment = NSTextAlignmentLeft;
    newPassWord.secureTextEntry = YES;
    newPassWord.tag = 555;
    newPassWord.delegate = self;
    newPassWord.clearButtonMode = UITextFieldViewModeWhileEditing;
    newPassWord.borderStyle = UITextBorderStyleRoundedRect;
    UIImageView *newPwdLeftView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    newPwdLeftView.image = [UIImage imageNamed:@"password"];
    newPwdLeftView.backgroundColor = [UIColor clearColor];
    newPassWord.leftView = newPwdLeftView;
    newPassWord.leftView.hidden = NO;
    newPassWord.leftViewMode  = UITextFieldViewModeAlways;
    newPassWord.returnKeyType  =  UIReturnKeyDone;
    [self.contentView addSubview:newPassWord];
    
    
    forggetButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [forggetButton setTitle:@"忘记密码?" forState:UIControlStateNormal];
    [forggetButton setTitle:@"忘记密码?" forState:UIControlStateHighlighted];
    forggetButton.frame = CGRectMake(width_x(newPassWord)-80, height_y(newPassWord)+5, 80, 30);
    [forggetButton addTarget:self action:@selector(forgetPass) forControlEvents:UIControlEventTouchUpInside];
    forggetButton.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    forggetButton.titleLabel.textColor = UIColorFromRGB(0x6f6254);
    [forggetButton setTitleColor:UIColorFromRGB(0x6f6254) forState:UIControlStateHighlighted];
    [forggetButton setTitleColor:UIColorFromRGB(0x6f6254) forState:UIControlStateNormal];
    [self.contentView addSubview:forggetButton];
    
    UIView * lv = [UIView initViewRect:CGRectMake(5, 23,70, 0.5) andBackGroudColor:UIColorFromRGB(0x6f6254)];
    [forggetButton addSubview:lv];
    
    comfirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
    comfirmButton.frame = CGRectMake(20, height_y(newPassWord)+55, (UI_SCREEN_WIDTH - 2*20), 40);
    comfirmButton.layer.masksToBounds = YES;
    comfirmButton.layer.cornerRadius = 6.0f;
 
    [comfirmButton setBackgroundImage:[UIImage imageNamed:@"pressedBg"] forState:UIControlStateHighlighted];
    [comfirmButton setBackgroundImage:[UIImage imageNamed:@"pressedBg"] forState:UIControlStateNormal];
    
    [comfirmButton setTitle:@"登录" forState:UIControlStateNormal];
    [comfirmButton addTarget:self action:@selector(comfirmButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    comfirmButton.titleLabel.font = [UIFont systemFontOfSize:17.0f];
    [self.contentView addSubview:comfirmButton];

    
    mrect1 = registerField.frame;
    mrect2 = newPassWord.frame;
    mrect3 = comfirmButton.frame;
    mrect4 = logoImageView.frame;
    mrect5 = forggetButton.frame;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark ====UITextFieldDEleget
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self comfirmButtonPressed];
    [textField resignFirstResponder];
    return  YES;
}

-(void)getVerifyCodeBtnPressed
{
    
}
-(void)comfirmButtonPressed
{
    [registerField resignFirstResponder];
    [newPassWord resignFirstResponder];
    if (![XDTools chickIphoneNumberRight:registerField.text]) {
        [XDTools showTips:@"请输入正确的手机号" toView:self.contentView];
        return;
    }
    
    if (newPassWord.text.length < 6 || newPassWord.text.length > 10) {
        [XDTools showTips:@"请输入6-10位密码" toView:self.contentView];
        return;
    }
    
    if(![XDTools NetworkReachable]){
        [XDTools showTips:brokenNetwork toView:self.view];
        return;
    }
    [XDTools showProgress:self.contentView];
    NSDictionary *requestDic = @{@"UserPass": newPassWord.text,@"UserName":registerField.text};
    ASIHTTPRequest *request = [XDTools postRequestWithDict:requestDic API:API_LOGIN];
    __weak ASIHTTPRequest * mrequest = request;
    [request setTimeOutSeconds:12];
    [request setCompletionBlock:^{
        [XDTools hideProgress:self.contentView];
        NSDictionary * tmpDict= [XDTools JSonFromString:mrequest.responseString];
        if ([[tmpDict objectForKey:@"status"] intValue] == 1) {
            [self initUserInfo:tmpDict];
            [self finishButtonPressed];
            if ([tmpDict[@"data"][@"voucher"] intValue]) {
                [XDTools sharedXDTools].haveYouHuiQuan = YES;
            }else{
                [XDTools sharedXDTools].haveYouHuiQuan = NO;
            }
            [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:@"isBackToOrderListToRefresh"];
            [XDTools showTips:@"登录成功" toView:self.contentView];
            
            [_delegate lReflashData];
            
            [APService setTags:[NSSet setWithObject:[NSString stringWithFormat:@"%@",tmpDict[@"data"][@"ID"]]] callbackSelector:nil object:nil];
            [self performSelector:@selector(delyaToPush) withObject:nil afterDelay:.8];
        }else{
            [XDTools showTips:[tmpDict objectForKey:@"msg"] toView:self.contentView];
        }
    }];
    [request setFailedBlock:^{
        [XDTools hideProgress:self.contentView];
        if (mrequest.error.code == 2) {
            [XDTools showTips:@"网络请求超时" toView:self.view];
        }
    }];
    [request startAsynchronous];
    
}

-(void)delyaToPush
{
    [self backPrePage];
//    [self.navigationController popViewControllerAnimated:YES];
}
-(void)initUserInfo:(NSDictionary *)userInfo
{
    
    if ([[userInfo objectForKey:@"data"] objectForKey:@"token"] && [[userInfo objectForKey:@"data"] objectForKey:@"ID"]) {
        [[NSUserDefaults standardUserDefaults]setObject:[[userInfo objectForKey:@"data"] objectForKey:@"ID"] forKey:kMY_USER_ID];
        [[NSUserDefaults standardUserDefaults]setObject:[[userInfo objectForKey:@"data"] objectForKey:@"token"] forKey:kMY_USER_TOKEN];
        [[NSUserDefaults standardUserDefaults]setObject:registerField.text forKey:kMY_USER_IPHONE];
        [[NSUserDefaults standardUserDefaults] setObject:userInfo[@"data"][@"Photo"] forKey:kMY_USER_FACE];
        [[NSUserDefaults standardUserDefaults] setObject:userInfo[@"data"][@"NickName"] forKey:kMY_USER_NAME];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }else{
        [XDTools showTips:@"服务器参数错误" toView:self.contentView];
    }

}
-(void)finishButtonPressed
{
    [registerField resignFirstResponder];
    [verifyCodeField resignFirstResponder];
    [newPassWord resignFirstResponder];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
//    if (textField.tag == 333) {
//        if (![XDTools chickIphoneNumberRight:textField.text]) {
//            [XDTools showTips:@"请输入正确的手机号码" toView:self.view];
//        }
//    }
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField.tag == 333) {
        if (textField.text.length >=11) {
            [XDTools showTips:@"请输入11位手机号" toView:self.view];
            registerField.text = [textField.text substringToIndex:10];
            return  YES;
        }
    }
    return  YES;
}
-(void)keyboardWillShow
{
   [UIView animateWithDuration:0.5 animations:^{
       if (iPhone5){
           registerField.frame = CGRectMake(registerField.frame.origin.x, mrect1.origin.y-50-80, registerField.frame.size.width, registerField.frame.size.height);
           newPassWord.frame = CGRectMake(newPassWord.frame.origin.x, mrect2.origin.y-50-80, newPassWord.frame.size.width, newPassWord.frame.size.height);
           comfirmButton.frame = CGRectMake(comfirmButton.frame.origin.x, mrect3.origin.y-50-80, comfirmButton.frame.size.width, comfirmButton.frame.size.height);
           logoImageView.frame = CGRectMake(logoImageView.frame.origin.x, mrect4.origin.y-50-80, logoImageView.frame.size.width, logoImageView.frame.size.height);
           forggetButton.frame = CGRectMake(forggetButton.frame.origin.x, mrect5.origin.y-50-80, forggetButton.frame.size.width, forggetButton.frame.size.height);
       }else{
           registerField.frame = CGRectMake(registerField.frame.origin.x, mrect1.origin.y-50-80-50, registerField.frame.size.width, registerField.frame.size.height);
           newPassWord.frame = CGRectMake(newPassWord.frame.origin.x, mrect2.origin.y-50-80-50, newPassWord.frame.size.width, newPassWord.frame.size.height);
           comfirmButton.frame = CGRectMake(comfirmButton.frame.origin.x, mrect3.origin.y-50-80-50, comfirmButton.frame.size.width, comfirmButton.frame.size.height);
           logoImageView.frame = CGRectMake(logoImageView.frame.origin.x, mrect4.origin.y-50-80-50, logoImageView.frame.size.width, logoImageView.frame.size.height);
           forggetButton.frame = CGRectMake(forggetButton.frame.origin.x, mrect5.origin.y-50-80-50, forggetButton.frame.size.width, forggetButton.frame.size.height);
       }
       
   }];
    
}
-(void)keyboardWillHide
{
    
    [UIView animateWithDuration:.5 animations:^{
        registerField.frame = CGRectMake(registerField.frame.origin.x,mrect1.origin.y, registerField.frame.size.width, registerField.frame.size.height);
        newPassWord.frame = CGRectMake(newPassWord.frame.origin.x, mrect2.origin.y, newPassWord.frame.size.width, newPassWord.frame.size.height);
        comfirmButton.frame = CGRectMake(comfirmButton.frame.origin.x, mrect3.origin.y, comfirmButton.frame.size.width, comfirmButton.frame.size.height);
        logoImageView.frame = CGRectMake(logoImageView.frame.origin.x, mrect4.origin.y, logoImageView.frame.size.width, logoImageView.frame.size.height);
        forggetButton.frame = CGRectMake(forggetButton.frame.origin.x, mrect5.origin.y, forggetButton.frame.size.width, forggetButton.frame.size.height);
    }];
}
-(void)registerButtonPressed
{
    RegisterViewController *registerVC = [[RegisterViewController alloc]init];
    [self.navigationController pushViewController:registerVC animated:YES];
//  RegisterFinishUserInfoViewController *push = [[RegisterFinishUserInfoViewController alloc]init];
//  [self.navigationController pushViewController:push animated:YES];
}
-(void)forgetPass
{
    forgetPasswordViewController *forget = [[forgetPasswordViewController alloc]init];
    [self.navigationController pushViewController:forget animated:YES];
}

-(void)backPrePage
{
    if (self.atype){
        if (self.atype == 1){
            [self dismissViewControllerAnimated:YES completion:^{
                
            }];
        }else{
            [self.navigationController popViewControllerAnimated:YES];
        }
    }else{
        [self.navigationController popViewControllerAnimated:YES];

    }
}




@end
